﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;

namespace GqqMvcWeb.Models.Database
{
    /// <summary>
    /// 建立连接字符串上下文，默认连接字符串为TutorialDBContext
    /// </summary>
    public class TutorialDBContext : DbContext
    {
//        public DbSet<student> Students { get; set; }
//        public DbSet<enrollment> Enrollments { get; set; }
//        public DbSet<course> Courses { get; set; }
        public DbSet<multkeys> Multkeys { get; set; }
        /// <summary>
        /// 重写OnModelCreating方法，可以修改好多东西。
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // 去除表的复数名字，这个很重要，不然累死你。
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            //可以使用这个方法，设置绑定的表名
//            modelBuilder.Entity<multkeys>().HasKey(x => x.id1);
//            modelBuilder.Entity<multkeys>().HasKey(x => x.id2);
            //设置主Key
            //modelBuilder.Entity<product>().HasKey(x => x.category_id);
            //这步不能写
            //            base.OnModelCreating(modelBuilder);
        }

        /// <summary>
        /// 重写ValidateEntity方法，由于Mysql和SqlServer处理机制不同，
        /// 如果更新内容与数据库的一致，SQLServer仍然会返回受影响行数为1，但是MySQL则会认为受影响行数为0。
        /// </summary>
        /// <param name="entityEntry"></param>
        /// <param name="items"></param>
        /// <returns></returns>
//        protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(System.Data.Entity.Infrastructure.DbEntityEntry entityEntry, IDictionary<object, object> items)
//        {
//            int wrongCount = 0;
//            int allCount = 0;
//            if (entityEntry.State == System.Data.EntityState.Modified)
//            {
//                foreach (var name in entityEntry.OriginalValues.PropertyNames)
//                {
//                    var prop = entityEntry.Property(name);
//                    if (prop.IsModified)
//                    {
//                        allCount++;
//                        if (prop.OriginalValue.Equals(prop.CurrentValue))
//                            wrongCount++;
//                    }
//
//                }
//                if (wrongCount == allCount)
//                    entityEntry.State = System.Data.EntityState.Unchanged;
//            }
//            return base.ValidateEntity(entityEntry, items);
//        }

    }
}